#include "space_ship.hpp"

#include "../debug.hpp"

namespace ps
{

SpaceShip::SpaceShip(): m_friction(0.1f), m_window(0), m_state(SpaceShip::DEAD)
{
}

void SpaceShip::Initialize()
{
	assert(NULL != m_window);

	sf::IntRect texture_rect(0, 0, 70, 65);
	m_ship_spr.SetSubRect(texture_rect);
	m_ship_spr.SetCenter(0.5f * (texture_rect.Right - texture_rect.Left),
			0.5f * (texture_rect.Bottom - texture_rect.Top));

	m_ship_spr.SetPosition(400.f, 300.f);

}

void SpaceShip::Update(float dt)
{
	sf::Vector2f pos = m_ship_spr.GetPosition();

	pos.x = pos.x + m_move_dir.x;
	pos.y = pos.y + m_move_dir.y;

	pos.x = (pos.x < 0) ? 0 : pos.x;
	pos.x = (pos.x > 800) ? 800 : pos.x;
	pos.y = (pos.y < 0) ? 0 : pos.y;
	pos.y = (pos.y > 600) ? 600 : pos.y;

	m_move_dir = m_move_dir * SpaceShip::m_friction;

	m_ship_spr.SetPosition(pos);
	const sf::Input& input = m_window->GetInput();
	glm::vec2 mouse_pos(input.GetMouseX(), input.GetMouseY());
	glm::vec2 ship_pos(m_ship_spr.GetPosition().x, m_ship_spr.GetPosition().y);
	glm::vec2 mouse_dir = mouse_pos - ship_pos;
	mouse_dir = glm::normalize(mouse_dir);
	glm::vec2 y_dir(0.f, -1.f);
	glm::vec2 x_dir(1.f, 0.f);
	float cos_alpha_y = glm::dot(mouse_dir, y_dir); // cos alpha
	float cos_alpha_x = glm::dot(mouse_dir, x_dir); // cos alpha
	float angl_rad = acos(cos_alpha_y);
	float angl_degree = glm::degrees(angl_rad);
	if (cos_alpha_x > 0)
	{
		angl_degree = 360 - angl_degree;
	}
	m_ship_spr.SetRotation(angl_degree);
}

void SpaceShip::MoveTo(float dx, float dy)
{
	m_move_dir.x += dx;
	m_move_dir.y += dy;
}

void SpaceShip::Render() const
{
	m_window->Draw(m_ship_spr);
}

SpaceShip::~SpaceShip()
{
}

} /* namespace lge2d */
